<template>
  <el-dialog
    class="g-dialog-wrapper d-dialog"
    v-model="dialogVisible"
    title="请输入图中字符"
    width="320px"
  >
    <div class="verify-wrap">
      <img class="image-verify-container-image" :src="codeImageSrc" alt="" @click="refreshCode" />
      <div class="input-wrap dflex-side-center">
        <el-input
          ref="imgRef"
          v-model="code"
          placeholder="请输入图片中的字符"
          :maxlength="4"
          size="large"
          clearable
          autofocus
          @keyup.enter="keyPress"
        />
        <el-button
          size="large"
          @click="loginConfirm"
          :loading="props.loading"
          type="primary"
          class="verify-btn"
          :disabled="verDisabled"
          >确 认</el-button
        >
      </div>
    </div>
  </el-dialog>
</template>

<script lang="ts" setup name="CVerifyCodeDialog">
import { defineExpose, defineProps, withDefaults, defineEmits, computed, ref, watch } from 'vue';
import { randomLenNum } from '@/utils';
import { verifyCodeImgUrl } from '@/apis/user/user';

interface CVerifyCodeDialogProps {
  visible: boolean;
  loading: boolean;
}
const props = withDefaults(defineProps<CVerifyCodeDialogProps>(), {});
const emits = defineEmits(['update:visible', 'confirm']);
const dialogVisible = computed<boolean>({
  get: () => {
    return props.visible;
  },
  set: val => {
    emits('update:visible', val);
  }
});
watch(
  () => dialogVisible.value,
  val => {
    if (val) {
      refreshCode();
    }
  }
);
const codeImageSrc = ref<string>('');
const randomStr = ref<string>('');
const code = ref<string>('');

// 刷新图像验证码
const refreshCode = () => {
  randomStr.value = randomLenNum(4, true);
  codeImageSrc.value = `${verifyCodeImgUrl}?randomStr=${randomStr.value}`;
  code.value = '';
};
const verDisabled = computed(() => {
  return code.value.length !== 4;
});

const keyPress = () => {
  if (!verDisabled.value) {
    loginConfirm();
  }
};

const loginConfirm = () => {
  emits('confirm');
};

function getVerifyCodeInfo() {
  return {
    randomStr: randomStr.value,
    code: code.value
  };
}

defineExpose({
  getVerifyCodeInfo,
  refreshCode
});
</script>

<style lang="scss" scoped>
.verify-wrap {
  padding: 16px 24px 16px 16px;
  img {
    width: 136px;
    height: 68px;
    margin-bottom: 16px;
    cursor: pointer;
  }
  .input-wrap {
    display: flex;
    .verify-btn {
      padding-left: 20px;
      padding-right: 20px;
      margin-left: 8px;
      font-size: 14px;
    }
  }
}
</style>
<style lang="scss">
.d-dialog .el-dialog__body {
  border-top: 1px solid $g-color-n6;
  padding: 0;
}
</style>
